/*
 * @Author: 邵明
 * @Date: 2019-06-14 12:02:15
 * @Last Modified by: 邵明
 * @Last Modified time: 2019-06-15 22:21:19
 */
import Cookies from 'js-cookie'
import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import store from '../index'
import _ from "lodash"
import { isUndefined, isArray } from 'util';
import { refresh as remoteRefresh, logoutPost as logout } from '../../services';


export interface ITokenType {
  access_token?: string | undefined;
  token_type?: string | undefined;
  expires_in?: number | undefined;
}

export interface IUserType {
  id?: number | undefined;
  email?: string | undefined;
  password?: string | undefined;
  remember?: boolean | undefined;
  name?: string | undefined;
  avatar_url?:string | undefined;
  created_at?:Date | undefined;
  updated_at?:Date | undefined;
}

export interface IUserState {
  _user?: IUserType | undefined;
  _token?: ITokenType | undefined;
}

@Module({ name: 'user', dynamic: true, store })
export class User extends VuexModule implements IUserState {

  public _token: ITokenType | undefined = {
    access_token: Cookies.get('jm_token'),
    token_type: Cookies.get('jm_token_type')
  };
  public _user: IUserType | undefined = undefined

  get token(): ITokenType | undefined {
    return this._token;
  }

  get user(): IUserType | undefined {
    return this._user;
  }

  get authCheck(): boolean {
    return !(isUndefined(this.token) || isUndefined(this.token.access_token));
  }

  @Action
  public async reLogin() {
    if (this.authCheck && isUndefined(this.user)) {
      return this.refresh();
    }
    return Promise.resolve(true);
  }

  @Action
  public async logout() {
    await logout();
    this.SAVE_TOKEN(undefined);
    this.SAVE_USER(undefined);
    return Promise.resolve(true);
  }

  @Action
  public async refresh() {
    let that = this;
    return remoteRefresh().then(function (resultData: any) {
      if (resultData.success) {
        let data = resultData.data;
        that.SAVE_TOKEN(data.token)
        that.SAVE_USER(data.user);
      }
      return Promise.resolve(true);
    }, function () {
      return Promise.reject(false);
    });
  }

  @Mutation
  public SAVE_TOKEN(token: ITokenType | undefined) {
    if (token) {
      let expires_in = token.expires_in ? token.expires_in : 6000;
      Cookies.set('jm_token', token.access_token as string, { expires: expires_in });
      Cookies.set('jm_token_type', token.token_type as string, { expires: expires_in });
    } else {
      Cookies.remove("jm_token");
      Cookies.remove("jm_token_type");
    }
    let newToken = _.pick(token, ['access_token','token_type','expires_in']);
    this._token = _.extend({},this._token,token);
  }

  @Mutation
  public SAVE_USER(user: any | undefined) {
    if(!user){
      this._user = undefined;
      return;
    }
    let newUser = _.pick(user, ['id','email','remember','name','avatar_url','created_at','updated_at']);
    if(isArray(user.avatar) && user.avatar.length > 0){
      let avatar = user.avatar[0];
      if(avatar.info && avatar.info.tiny_thumbnail){
          newUser.avatar_url = avatar.info.tiny_thumbnail;
      }else {
        newUser.avatar_url = avatar.url;
      }
    }

    this._user = _.extend({},this._user,newUser);
  }

  @Mutation
  public REMOVE_USER() {
    Cookies.remove("jm_token");
    Cookies.remove("jm_token_type");
    this._user = undefined;
    this._token = undefined;
  }
}

export const UserModule = getModule(User);
